/**登录相关的状态 */
import { makeObservable, observable, action } from "mobx";
import { Auth } from "../models/index";
import UserStore from "./user";
import {message} from "antd"


class AuthStore {
  @observable isLogin = false;
  @observable isLoading = false;
  @observable values = {
    username: "",
    password: "",
  };

  @action setIsLogin(isLogin) {
    this.isLogin = isLogin;
  }
  @action setIsLoading(isLoading) {
    this.isLoading = isLoading;
  }
  @action setIsUsername(username) {
    this.values.username = username;
  }
  @action setIsPassword(password) {
    this.values.password = password;
  }
  // 登录
  @action login() {
    return new Promise((resolve, reject) => {
      Auth.login(this.values.username, this.values.password)
        .then((response) => {
          UserStore.pullUser()
          resolve(response);
        })
        .catch((error) => {
          message.error('登录失败,请核对账户密码或用户是否存在');
          reject(error);
        });
    });
  }
  // 注册
  @action register() {
    return new Promise((resolve, reject) => {
      Auth.register(this.values.username, this.values.password)
        .then((response) => {
          UserStore.pullUser()
          resolve(response);
        })
        .catch((error) => {
          message.error('注册失败,用户名已被占用');
          UserStore.resetUser()
          reject(error);
        });
    });
  }
  // 注销
  @action logout() {
    Auth.logout();
    UserStore.resetUser()
  }
  // 兼容mobex6.0版本
  constructor() {
    makeObservable(this);
  }
}

export default new AuthStore();
